package com.zxy.zxyrpc.serializer;

import com.zxy.zxyrpc.exception.RpcException;
import com.zxy.zxyrpc.model.ErrorCode;

import java.io.*;

/**
 * JDK 序列化器
 *
 * @author zxy
 * @since 2025/5/11
 **/
public class JdkSerializer implements Serializer {
    @Override
    public <T> byte[] serialize(T object) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream objectStream = new ObjectOutputStream(bos);
        objectStream.writeObject(object);
        objectStream.close();

        return bos.toByteArray();
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> type) throws IOException {
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        try (ObjectInputStream objectStream = new ObjectInputStream(is)) {
            return (T) objectStream.readObject();
        } catch (ClassNotFoundException e) {
            throw new RpcException(ErrorCode.SYSTEM_ERROR, "JDK反序列失败");
        }
    }
}
